package cn.wjssl.domain.strategy.service.rule.chain.impl;

import cn.wjssl.domain.strategy.repository.IStrategyRepository;
import cn.wjssl.domain.strategy.service.rule.chain.AbstractLogicChain;
import cn.wjssl.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import cn.wjssl.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author：lxd
 * @Description 黑名单抽奖方式
 * @Date：2025/2/10
 */
@Slf4j
@Component("rule_blacklist")
public class BlackListLogicChain extends AbstractLogicChain {

    @Resource
    private IStrategyRepository repository;

    @Override
    protected String currentRuleModel() {
        return DefaultChainFactory.LogicModel.RULE_BLACKLIST.getCode();
    }

    /**
     * 黑名单抽奖
     * @param userId     用户ID
     * @param strategyId 策略ID
     * @return 责任链抽奖流转对象
     */
    @Override
    public DefaultChainFactory.StrategyAwardVO logicChain(String userId, Long strategyId) {
        log.info("抽奖责任链-黑名单开始 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, currentRuleModel());

        // 查询Strategy_rule表 获取对应的 rule_value, 100:user001,user002,user003
        String ruleValue = repository.queryStrategyRuleValue(strategyId, currentRuleModel(), null);
        // 根据冒号分割
        String[] ruleValueSplit = ruleValue.split(Constants.COLON);
        // 获取黑名单对应的奖品awardId
        Integer blackListAwardId = Integer.parseInt(ruleValueSplit[0]);
        // 获取黑名单用户
        String[] blackIdsList = ruleValueSplit[1].split(Constants.SPLIT);
        // 遍历, 和抽奖对象的 userId 对比
        for (String userBlackId : blackIdsList) {
            if (userId.equals(userBlackId)) {
                return DefaultChainFactory.StrategyAwardVO.builder()
                        .awardId(blackListAwardId)
                        .logicModel(currentRuleModel())
                        // 写入默认配置黑名单奖品值 0.01 ~ 1 积分，也可以配置到数据库表中
                        .awardConfig("0.01,1")
                        .build();
            }
        }

        // 如果不是黑名单, 那继续下一个过滤链的过滤方法
        log.info("抽奖责任链-黑名单放行 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, currentRuleModel());
        return next().logicChain(userId, strategyId);
    }

}
